<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示删除号) show-icon(显示图标) -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="medium"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="shuju">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, index) in shuju.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClosed(index, shuju.row)"
                  :resizable="false"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="shuju.row.inputVisible"
                  v-model="shuju.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(shuju.row)"
                  @blur="handleInputConfirm(shuju.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(shuju.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :resizable="false"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
              :resizable="false"
            ></el-table-column>
            <el-table-column label="操作" :resizable="false">
              <template v-slot="shuju">
                <!-- 编辑按键 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDiolog(shuju.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按键 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="deleteParamsById(shuju.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="medium"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" style="width: 100%" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="shuju">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, index) in shuju.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClosed(index, shuju.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="shuju.row.inputVisible"
                  v-model="shuju.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(shuju.row)"
                  @blur="handleInputConfirm(shuju.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(shuju.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :resizable="false"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
              :resizable="false"
            ></el-table-column>
            <el-table-column label="操作" :resizable="false">
              <template v-slot="shuju">
                <!-- 编辑按键 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDiolog(shuju.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按键 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="deleteParamsById(shuju.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数的表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      // 选中的的分类ID数组
      selectedKeys: [],
      // 被激活的页签名称
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 添加对话框是否显示
      addDialogVisible: false,
      // 添加参数的表单数据
      addForm: {
        attr_name: '',
      },
      // 添加表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数！', trigger: 'blur' },
        ],
      },
      // 编辑对话框是否展示
      editDialogVisible: false,
      // 编辑参数的表单数据
      editForm: {
        attr_name: '',
      },
      // 编辑表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数！', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '获取商品分类数据失败！',
          type: 'error',
        })
      }
      // 将数据列表赋值给cateList
      this.cateList = res.data
    },
    // 当用户在级联菜单中选择内容改变时触发
    handleChange() {
      this.getParamsData()
    },
    // tab 页签点击事件处理函数
    handleClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      // 证明选中的不是三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 证明选中的是三级分类
      // console.log(this.selectedKeys)
      // 根据所选分类的ID和当前所处的面板，获取对应参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '获取分类参数列表失败！',
          type: 'error',
        })
      }
      // 将attr_vals拆分为数组，进行保存
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框与按钮的切换显示
        item.inputVisible = false
        // 文本框中输入的内容
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message({
            duration: 2000,
            message: '添加参数失败！',
            type: 'error',
          })
        }
        this.$message({
          duration: 2000,
          message: '添加参数成功！',
          type: 'success',
        })
        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    // 展示编辑对话框
    async showEditDiolog(attrId) {
      // 查询当前参数的信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '查询参数失败！',
          type: 'error',
        })
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改（编辑）参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message({
            duration: 2000,
            message: '修改参数失败！',
            type: 'error',
          })
        }
        this.$message({
          duration: 2000,
          message: '修改参数成功！',
          type: 'success',
        })
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 根据id删除参数
    async deleteParamsById(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //  如果用户确认删除，则返回值为 confirm
      //  如果用户取消删除，则返回值为 cancel
      if (confirmResult !== 'confirm') {
        return this.$message({
          duration: 2000,
          message: '取消删除参数！',
          type: 'info',
        })
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '删除参数失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '删除参数成功！',
        type: 'success',
      })
      // 重新渲染参数列表
      this.getParamsData()
    },
    // 文本框失去焦点 或者按下enter键触发
    async handleInputConfirm(params) {
      if (params.inputValue.trim() === '') {
        params.inputValue = ''
        params.inputVisible = false
        return
      }
      // 如果没有return，则证明输入了内容
      // 需要添加新的动态参数
      params.attr_vals.push(params.inputValue.trim())
      params.inputValue = ''
      params.inputVisible = false
      // 发起请求，保存数据
      this.saveAttrVals(params)
    },
    // 点击按钮展示输入框
    showInput(row) {
      row.inputVisible = true
      // 自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //  删除对应的参数可选项
    handleClosed(index, params) {
      params.attr_vals.splice(index, 1)
      // 发起请求，保存数据
      this.saveAttrVals(params)
    },
    // 将对 attr_vals 的操作，保存到数据库
    async saveAttrVals(params) {
      // 发起请求，保存数据
      const { data: res } = await this.$http.put(
        `categories/${params.cat_id}/attributes/${params.attr_id}`,
        {
          attr_name: params.attr_name,
          attr_sel: params.attr_sel,
          attr_vals: params.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '修改参数项失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '修改参数项成功！',
        type: 'success',
      })
    },
  },
  computed: {
    // 如果按钮需要被禁用时，返回true；反之返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) return true
      else return false
    },
    // 当前选中的三级分类ID
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 动态计算标题文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else return '静态属性'
    },
  },
}
</script>

<style scoped>
.cat_opt {
  margin-top: 20px;
}

.el-cascader {
  width: 300px;
}

.el-tabs {
  margin-top: 20px;
}

.el-tag {
  margin: 15px;
}

.button-new-tag {
  margin-left: 15px;
}

.input-new-tag {
  margin-left: 15px;
  width: 150px;
}
</style>
